import dayjs from 'dayjs'
import { localGet } from '@/utils/index'
import { getAMapPosition } from '@/utils/initAMap'
import { localGetApplicationId } from '@/utils/common';

// 增加水印
export const customAddWaterMarkFunc = (file, text = []) => {
  return new Promise(resolve => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      const img = document.createElement('img')
      img.src = reader.result
      img.setAttribute('crossOrigin', 'Anonymous')
      img.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = img.naturalWidth
        canvas.height = img.naturalHeight
        const ctx = canvas.getContext('2d')
        ctx.fillRect(0, 0, canvas.width, canvas.height)
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
        ctx.fillStyle = '#fff'
        ctx.textBaseline = 'middle'
        const spaceH = 4
        text?.forEach((item, index) => {
          if (index === 0) {
            // 文字样式
            ctx.font = '400 16px PingFangSC-Regular '
            ctx.fillText(item, 24, 30)
          } else {
            ctx.font = '400 12px PingFangSC-Regular '
            ctx.fillText(item, 24, 30 + spaceH + index * 20)
          }
        })
        canvas.toBlob(resolve)
      }
    }
  })
}

// 获取水印文字
// 用户 时间 地址
export const generateWaterMarkText = async () => {
  const userInfo = localGetApplicationId("al__USER_INFO") || localGet('al__USER_INFO')
  const text = []
  // 用户
  if (userInfo.name) {
    text.push(userInfo.name)
  }
  // 时间
  const now = dayjs().format('HH:mm:ss YYYY-MM-DD') + ' ' + convertWeek(dayjs().day())
  if (now) {
    text.push(now)
  }
  // 位置信息
  const formattedAddress = await getAMapPosition()
  if (formattedAddress) {
    text.push(formattedAddress)
  }
  return text
}

// 转化星期值
export const convertWeek = value => {
  switch (value) {
    case 1:
      return '星期一'
    case 2:
      return '星期二'
    case 3:
      return '星期三'
    case 4:
      return '星期四'
    case 5:
      return '星期五'
    case 6:
      return '星期六'
    case 0:
      return '星期日'
    default:
      return '星期日'
  }
}
